package ldh.im.fxbase.socket;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import ldh.im.handle.FileSendHandler;

import java.io.File;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class FileTransferClient {

    private ThreadPoolExecutor executorService = (ThreadPoolExecutor) Executors.newFixedThreadPool(3);
    private Deque<Channel> channels = new ArrayDeque<>();

    public FileTransferClient() {
        executorService.setKeepAliveTime(20, TimeUnit.SECONDS);
        executorService.allowCoreThreadTimeOut(true);
    }

    public void sendFile(File file) {

    }

    private Channel newChannel(String host, int port) {
        Channel channel = channels.getFirst();
        if (channel == null) {
            NettyChannel nettyChannel = new NettyChannel(host, port);
            channel = nettyChannel.getChannel();
        }
        return channel;
    }

    private class NettyChannel {
        private Channel channel = null;
        private Bootstrap clientBootstrap;
        private NioEventLoopGroup group;
        private String host;
        private int port;

        public NettyChannel(String host, int port) {
            this.host = host;
            this.port = port;
        }

        public void start() {
            try {
                buildClient();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        private void buildClient() throws InterruptedException {
            group = new NioEventLoopGroup(1);
            clientBootstrap = new Bootstrap();
            clientBootstrap.group(group)
                    .channel(NioSocketChannel.class)  // 使用NioSocketChannel来作为连接用的channel类
                    .handler(new ChannelInitializer<SocketChannel>() { // 绑定连接初始化器
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new FileSendHandler());
                        }
                    });
            ChannelFuture f = clientBootstrap.connect(host, port).sync();
            channel = f.channel();
            f.channel().closeFuture().sync();
        }

        public Channel getChannel() {
            return channel;
        }

        public void close() {
            if (channel.isActive()) {
                channel.close();
            }
            group.shutdownGracefully();
        }
    }


}


